<template>
  <!-- 头部 -->
  
  <div class="dept_where">
    <span>库区名称：</span><el-input class="dept_input" v-model="zone_name" style="width: 240px" />
    <el-button type="primary" class="" @click="queryZone()">查询</el-button>
    <el-button @click="reset">重置</el-button>
    <el-button type="success" @click="addWarehouseareaInfo()">
    
      <span>新增</span>
    </el-button>
    <el-button @click="fhlocation()">返回</el-button>
  </div>



  <el-table :data="tableData" :header-cell-style="{
      textAlign: 'center',
      background: '#f5f7fa',
      fontWeight: 'bold',
      position: 'sticky',
      top: 0
    }" :cell-style="{ textAlign: 'center', }" style="width: 100%" border>

    <el-table-column prop="zone_code" label="库区编码" show-overflow-tooltip>
      <template #default="scope">
        <span style="cursor: pointer; color: #409EFF;" @click="detail(scope.row)">
          {{ scope.row.zone_code }}
        </span>
      </template>
    </el-table-column>
    <el-table-column prop="zone_name" label="库区名称" show-overflow-tooltip>
    </el-table-column>
    <el-table-column prop="zone_capacity" label="库区容量" show-overflow-tooltip>
    </el-table-column>
    <el-table-column prop="zone_available" label="库区可用容量" show-overflow-tooltip>
    </el-table-column>

    <el-table-column prop="zone_freeze" label="是否冻结" show-overflow-tooltip>
      <template #default="scope">
        <div class="switch-wrapper">
          <!-- 状态标签 -->
          <span class="status-label">
            {{ scope.row.zone_freeze === "1" ? '是（已冻结）' : '否（未冻结）' }}
          </span>




          <!-- 可点击的开关 -->
          <div class="switch-display" :class="{ 'switch-on': Number(scope.row.zone_freeze) === 1 }" role="switch"
            :aria-checked="scope.row.zone_freeze === '1'" @click="toggleFreeze(scope.row)" tabindex="0"
            aria-label="点击切换冻结状态">
            <span class="slider"></span>
          </div>
        </div>
      </template>
    </el-table-column>

    <el-table-column label="操作" width="280" show-overflow-tooltip>
      <template #default="scope">
        <div class="action-buttons">
          <el-button type="primary" size="small" @click="WarehousearLocationcilck(scope.row.zone_code)">库位</el-button>
          <el-button size="small" @click="warehouse_zone_update(scope.row)">修改</el-button>
          <el-button type="danger" size="small" @click="warehouseDelete(scope.row)">删除</el-button>
        </div>
      </template>
    </el-table-column>

  </el-table>


  <!-- 分页 -->
  <div class="block">
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
      :page-sizes="[5,10, 20, 30]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
      :total="pageCount">
    </el-pagination>
  </div>



  <!--右边侧边栏-->
  <el-drawer v-model="dialogVisible" :title="title" :direction="direction" :before-close="handleClose" size="30%"
    :show-close="false" @close="close">
    <div style="display: flex; justify-content: center; height: 100%;">

      <el-form name="configfilefirstkindForm" method="post" ref="ruleFormRef" :model="WarehouseareaInfo" :rules="rules"
        style="width: 80%; margin-top: 20px;">

        <el-form-item prop="zone_code" label="库区编码" style="justify-content: center;">
          <div style="display: flex; align-items: center; gap: 10px;">
            <!-- 输入框禁用 -->
            <el-input v-model="WarehouseareaInfo.zone_code" placeholder="仓库编码" clearable style="width: 50%;"
              :disabled="WarehouseareaInfo.auto_generate_code === '1' || WarehouseareaInfo.isEditMode" />

            <!-- 开关禁用 -->
            <el-switch v-model="WarehouseareaInfo.auto_generate_code" :active-value="'1'" :inactive-value="'0'"
              @change="handleAutoGenerateCodeChange" active-color="#13ce66" inactive-color="#ff4949"
              :disabled="WarehouseareaInfo.isEditMode" />
            <span style="color: blue;"> 自动生成 </span>
          </div>
        </el-form-item>

        <el-form-item prop="zone_name" label="库区名称" style="justify-content: center;">
          <el-input v-model="WarehouseareaInfo.zone_name" placeholder="库区名称" clearable style="width: 100%;" />
        </el-form-item>

        <el-form-item label="库区容量　" style="justify-content: center;">
          <el-input-number v-model="WarehouseareaInfo.zone_capacity" :min="0" @change="handleCapacityChange" />
        </el-form-item>


        <el-form-item label="以用容量　" style="justify-content: center;">
          <el-input-number v-model="WarehouseareaInfo.zone_available" :min="0" :disabled="isDisabled"
            @change="changeCapacity_available" />
        </el-form-item>



        <el-form-item label="产品混放　" style="justify-content: center;" v-if="isTooltipEnabled">

          <el-tooltip content="点击设置该库区下所有库位允许产品混放" placement="top">
            <el-button type="primary"
              @click="toggleAllowProductMix(WarehouseareaInfo.zone_mixing, WarehouseareaInfo.zone_id)">允许</el-button>
          </el-tooltip>
          <el-tooltip content="点击设置该库区下所有库位不允许产品混放" placement="left">
            <el-button type="success"
              @click="toggleAllowProductMixNo(WarehouseareaInfo.zone_mixing, WarehouseareaInfo.zone_id)">不允许</el-button>
          </el-tooltip>

        </el-form-item>

        <el-form-item label="批次混放　" style="justify-content: center;" v-if="isTooltipEnabled">
          <el-tooltip content="点击设置该库区下所有库位允许批次混放" placement="top">
            <el-button type="primary" @click="toggleAllowBatchMix(WarehouseareaInfo.zone_id)">允许</el-button>
          </el-tooltip>
          <el-tooltip content="点击设置该库区下所有库位不允许批次混放" placement="left">
            <el-button type="success" @click="toggleAllowBatchMixNo(WarehouseareaInfo.zone_id)">不允许</el-button>
          </el-tooltip>
        </el-form-item>



        <el-form-item label="　备注信息" style="justify-content: center;">
          <el-input type="textarea" :rows="2" v-model="WarehouseareaInfo.remarks" placeholder="备注" clearable
            style="width: 100%;" />
        </el-form-item>

      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer" style="text-align: center;">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="WarehouseareaInfoAdd">确定</el-button>
      </div>
    </template>
  </el-drawer>
  <!--模态框-->
  <el-dialog title="查看库区" width="30%" v-model="dialogVisibleSwer">
    <div style="display: flex; justify-content: center; height: 100%;">
      <el-form name="configfilefirstkindForm" :disabled="true" method="post" :model="WarehouseareaInfo"
        style="width: 80%; margin-top: 20px;">

        <el-form-item prop="zone_code" label="　库区编码" style="justify-content: center;">

          <!-- 输入框禁用 -->
          <el-input v-model="WarehouseareaInfo.zone_code" placeholder="仓库编码" clearable style="width: 50%;" />

        </el-form-item>

        <el-form-item prop="zone_name" label="　库区名称" style="justify-content: center;">
          <el-input v-model="WarehouseareaInfo.zone_name" placeholder="库区名称" clearable style="width: 50%;" />
        </el-form-item>

        <el-form-item label="库区容量　" style="justify-content: center;">
          <el-input-number v-model="WarehouseareaInfo.zone_capacity" :min="0" @change="handleCapacityChange" />
        </el-form-item>


        <el-form-item label="以用容量　" style="justify-content: center;">
          <el-input-number v-model="WarehouseareaInfo.zone_available" :min="0" :disabled="isDisabled"
            @change="changeCapacity_available" />
        </el-form-item>
        <el-form-item label="　备注信息" style="justify-content: center;">
          <el-input type="textarea" :rows="2" v-model="WarehouseareaInfo.remarks" placeholder="备注" clearable
            style="width: 100%;" />
        </el-form-item>

      </el-form>
    </div>
    <span class="dialog-footer">
      <el-button @click="gbmtk">取消</el-button>
      <el-button type="primary" @click="confirmLoss">返回</el-button>
    </span>
  </el-dialog>



</template>
  
    <script setup>
    import { ref,onMounted,reactive } from 'vue'
    import axios from 'axios';
    import { useWarehouseStore } from '@/storejs/warehouseStore'
    import dayjs from 'dayjs'
    import { ElMessage, ElMessageBox } from 'element-plus';
    import { useRouter } from 'vue-router';

    

    //页面跳转获取数据
    const warehouseStore = useWarehouseStore()
    const warehouse_codego = ref(warehouseStore.warehouseCode) 


    const tableData = ref([]);// 表格数据对象
  
    var zone_name=ref('')//仓库名称
  
    const currentPage = ref(1)//当前页
  
    const ruleFormRef = ref();

    const pageSize = ref(5)//每页显示数
  
    const pageCount = ref(0)//总记录数

    const dialogVisible = ref(false)//右边侧边栏显示

    const title = ref("添加库区信息")
    //控制产品混放和产品批次混放的显示-默认为false
    var isTooltipEnabled=ref(false);


    const isDisabled = ref(true);


    //模态框的显示
    const dialogVisibleSwer = ref(false);

    //禁用库存容量的变量触发器
    const enableChangeEvent = ref(true);

    //判断确定是添加还是修改
    var warehousezone_id=ref(0);


    //创建路由实例
    var router=useRouter();


    //点击库位进行跳转
    function WarehousearLocationcilck(zone_code){
      const warehousezoneStore = useWarehouseStore();
      warehousezoneStore.zone_code=zone_code;

      router.push('/main/DB/WarehousearLocation')
    }

    //返回上一级
    function fhlocation() {
      router.push('/main/DB/WarehouseInfo');
    }
    
//控制 Element Plus 的抽屉Drawer组件从哪个方向滑出。
  const direction = ref('rtl')
    //初始化数据对象
    let intWarehouseInfo={
      zone_code:"",
      warehouse_code:warehouse_codego.value,
      zone_name:"",
      zone_capacity:0,
      zone_available:0,//库区可用容量,默认为zone_capacity
      zone_freeze:"0",//是否冻结
      zone_mixing:"0",//是否混仓
      zone_batch_mixing:"0",//是否批次混仓
      remarks:"",
      Create_by: localStorage.getItem('userLName'),
      Create_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
      update_by:"",//修改人
      Update_time:"",
      Del_flag: '0',
      auto_generate_code:'0',//是否自动生成仓库编码
      isEditMode: false,//是否是编辑模式
    }
 //模态对象
 const WarehouseareaInfo =reactive({...intWarehouseInfo})

    let Swer={
      zone_id: 0,
      zone_mixing: '0',//是否混仓,
      zone_batch_mixing:'0'
    }

    const WarehouseareaInfoSwer =reactive({...Swer})
    
 // 表单验证规则（示例）
const rules = reactive({
  zone_code: [
    { required: true, message: '库区编码不能为空', trigger: 'blur' }
  ],
  zone_name:[
    { required: true, message:'库区名称不能为空',trigger:'blur'}
  ]
})
    //判断库区编码是否存在
    async function WarehouseZone_code_judgment() {
     
      try {
        const res = await axios.get("http://localhost:5181/api/Db_warehouse_zone/WarehousezoneCodejudgment", {
          params: { 
            zone_code: WarehouseareaInfo.zone_code,
            warehouse_code: warehouse_codego.value
          },
          authorization: `Bearer ${localStorage.getItem('token')}`,
        });
        
        if (res.data > 0) {
          ElMessage.error('仓库编码已存在');
          
          return false;
        }
        console.log('请求成功:', res.data);
        return true;

      } catch (err) {
        console.error('请求失败:', err);
        return false;
      }
    }

    //判断库区名称是否存在
    async function  Warehousezone_name_judgment(){
    
      try {
        const res = await axios.get("http://localhost:5181/api/Db_warehouse_zone/WarehousezoneNamejudgment", {
          params: {
            zone_name: WarehouseareaInfo.zone_name,
            warehouse_code: warehouse_codego.value
          },
          authorization: `Bearer ${localStorage.getItem('token')}`,
        });

        if (res.data > 0) {
          ElMessage.error('库区域名称已存在');

          return false;
        }
        return true;

      } catch (err) {
        console.error('请求失败:', err);
        return false;
      }
    }



    // 判断库区名称修改是否存在--修改
    async function Warehousezone_name1_judgment_update() {
      try {
        const res = await axios.get("http://localhost:5181/api/Db_warehouse_zone/Warehousezone_name_UpdateJudgment", {
          params: {
            zone_name: WarehouseareaInfo.zone_name,
            warehouse_code: warehouse_codego.value,
            zone_code: WarehouseareaInfo.zone_code // 传递当前库区的主键
          },
          headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
          }
        });

        if (res.data > 0) { // 如果返回值大于0，说明存在重复
          ElMessage.error('库区域名称已存在');
          return false;
        }
        return true;
      } catch (err) {
        console.error('请求失败:', err);
        return false;
      }
    }



  
    //逻辑删除
    function warehouseDelete(row) {
      ElMessageBox.confirm(
        `你确定要删除编号为 ${row.zone_code} 的库区吗？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          axios.put(
            "http://localhost:5181/api/Db_warehouse_zone/warehouseZone_tombstone",
            {}, // put 请求如果没有 body 数据可以传空对象
            {
              params: {
                warehouse_code: row.warehouse_code,
                zone_code: row.zone_code
              },
              headers: {
                Authorization: localStorage.getItem("token")
              }
            }
          )
            .then((result) => {
              if (result.data > 0) {
                ElMessage.success(`库区${row.zone_name}删除成功`)
                Count();
                fill();
              } else {
                ElMessage.success(`库区中还有库存不可以或者是还有库位不可以删除`)
              }

            })
            .catch((err) => {
              console.error(err);
            });
        })
     
    }
    //添加的时候判断库区的容量不可以超过库位容量
    async function Warehousezone_Capacity_judgment(){
      try {
        const res = await axios.get("http://localhost:5181/api/Db_warehouse_zone/WarehousezoneCapacityjudgment", {
          params: {
            warehouse_code: WarehouseareaInfo.warehouse_code,
            zone_capacity: WarehouseareaInfo.zone_capacity
          },
          headers: { Authorization: localStorage.getItem("token") }
        });

        if (res.data > 0) {
          return true; // ✅ 合法
        } else {
          ElMessage.error('库区容量不可以大于仓库容量');
         
          return false; // ❌ 不合法
        }
      } catch (err) {
        console.error('请求失败:', err);
        return false;
      }
    }
    //库区修改的容量判断
    async function Warehousezone_Capacity_judgment_update() {
      try {
        const res = await axios.get("http://localhost:5181/api/Db_warehouse_zone/Warehousezone_Capacity_judgment_update", {
          params: {
            warehouse_code: WarehouseareaInfo.warehouse_code,
            zone_code: WarehouseareaInfo.zone_code,
            new_zone_capacity: WarehouseareaInfo.zone_capacity
          },
          headers: { Authorization: localStorage.getItem("token") }
        });

        if (res.data > 0) {
          return true; // ✅ 合法
        } else {
          ElMessage.error('库区容量不可以大于仓库容量');

          return false; // ❌ 不合法
        }
      } catch (err) {
        console.error('请求失败:', err);
        return false;
      }
    }



//添加和修改
async function WarehouseareaInfoAdd(){
  
  if (warehousezone_id ==0){
//添加
ruleFormRef.value.validate(async(valid)=>{
  if(valid){
    const isCodeValid = WarehouseZone_code_judgment();   // 启动第一个检查
    const isNameValid = Warehousezone_name_judgment();  // 启动第二个检查
    const isCapacityValid = Warehousezone_Capacity_judgment();  // 启动第三个检查
 
    //这行代码的作用是 并发执行多个异步任务（Promise然后将它们的结果 解构赋值 给对应的变量。
    const [codeValid, nameValid, isCapacityValidnr] = await Promise.all([isCodeValid, isNameValid, isCapacityValid]);

    console.log(nameValid, codeValid, isCapacityValidnr); // 输出第一个检查的结果
    if (!codeValid || !nameValid || !isCapacityValidnr) {
      console.log('库区编码或名称重复，无法提交');
      return;
    }
  
    axios.put("http://localhost:5181/api/Db_warehouse_zone/WarehousezoneAdd", WarehouseareaInfo,{
      headers: {
        authorization: `Bearer ${localStorage.getItem('token')}`,
      }
    }).then((res)=>{
      if(res.data>0){
        //提示
        ElMessage.success('添加成功')
        //关闭右边侧边栏
        dialogVisible.value=false;
        //清空数据
        Object.assign(WarehouseareaInfo,intWarehouseInfo)
        //统计方法
        Count();
        //重新查询
        fill();
      
        
      }else{
        ElMessage.error('添加失败')
      }


    }).catch((err)=>{
      console.log(err)
    })
    

  }
})
    
    }else{
   
    //修改仓库库区判断名称是否重复
    const isNameValid = Warehousezone_name1_judgment_update();  // 启动第二个检查
    const isCapacityValid = Warehousezone_Capacity_judgment_update();  
  
    const [nameValid, isCapacityValidSwer] = await Promise.all([isNameValid, isCapacityValid]);
    console.log(nameValid, isCapacityValidSwer); // 输出第一个检查的结果
    if (!nameValid || !isCapacityValidSwer) {
      console.log('仓库编码或名称重复，无法提交');
      return;
    }
    axios.put("http://localhost:5181/api/Db_warehouse_zone/WarehousezoneUpdate", WarehouseareaInfo,{
      headers: {
        authorization: `Bearer ${localStorage.getItem('token')}`,
      }
    }).then((res)=>{
      if(res.data>=0){
        ElMessage.success('修改成功');
        //关闭弹窗
        dialogVisible.value = false;
        //清空数据
        Object.assign(WarehouseareaInfo,intWarehouseInfo)
        //刷新数据
        fill()
        //刷新Count
        Count();
      }
    }).catch((err)=>{
    console.log(err)
    })



    }
}

    //产品混放允许按钮
   function toggleAllowProductMix(zone_mixing, id) {
   
     WarehouseareaInfoSwer.zone_id = id;
   
     WarehouseareaInfoSwer.zone_mixing = '1'
   
      ElMessageBox.confirm(
        '确认要重置库区下所有库位的产品混放规则吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
     

        axios.put(
          'http://localhost:5181/api/Db_warehouse_zone/Warehousezone_ProductMix',
          WarehouseareaInfoSwer,
          {
            headers: {
              authorization: `Bearer ${localStorage.getItem('token')}`,
              
            }
          }
        )
          .then((res) => {
          
            if (res.data > 0) {
              ElMessage.success(`产品混放规则设置成功`)
              //调用重新查询
              fill();
              //统计方法
              Count();
              
            } else if (res.data == 0) {
              ElMessage.success(`产品混放规则设置成功`)
            }else{
              ElMessage.error("设置失败，请重试");
            }
          })
          .catch((err) => {
            console.error(err)
            ElMessage.error('请求出错，请检查网络或稍后再试')
          })
      })
        .catch(() => {
          ElMessage.info('已取消操作')
        })
    }
  
    //产品混放不允许按钮
    function toggleAllowProductMixNo(zone_mixing,id){

      WarehouseareaInfoSwer.zone_id = id;

      WarehouseareaInfoSwer.zone_mixing = '0'

      ElMessageBox.confirm(
        '确认要重置库区下所有库位的产品混放规则吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        axios.put(
          'http://localhost:5181/api/Db_warehouse_zone/Warehousezone_ProductMixNO',
          WarehouseareaInfoSwer,
          {
            headers: {
              authorization: `Bearer ${localStorage.getItem('token')}`,
           
            }
          }
        )
          .then((res) => {

            if (res.data > 0) {
              ElMessage.success(`产品混放规则设置成功`)
              //调用重新查询
              fill();
              //统计方法
              Count();
            } else if (res.data == 0) {
              ElMessage.success(`产品混放规则设置成功`)
            } else {
              ElMessage.error("设置失败，请重试");
            }
          })
          .catch((err) => {
            console.error(err)
            ElMessage.error('请求出错，请检查网络或稍后再试')
          })
      })
        .catch(() => {
          ElMessage.info('已取消操作')
        })
    }
    //批次混放允许按钮
    function toggleAllowBatchMix(id){

      WarehouseareaInfoSwer.zone_id = id;

      WarehouseareaInfoSwer.zone_batch_mixing = '1'

      ElMessageBox.confirm(
        '确认要重置库区下所有库位的批次混放规则吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        axios.put(
          'http://localhost:5181/api/Db_warehouse_zone/Warehousezone_BatchMix',
          WarehouseareaInfoSwer,
          {
            headers: {
              authorization: `Bearer ${localStorage.getItem('token')}`,

            }
          }
        )
          .then((res) => {

            if (res.data > 0) {
              ElMessage.success(`产品批次混放规则设置成功`)
              //调用重新查询
              fill();
              //统计方法
              Count();
            } else if (res.data == 0) {
              ElMessage.success(`产品批次混放规则设置成功`)
            } else {
              ElMessage.error("设置失败，请重试");
            }
          })
          .catch((err) => {
            console.error(err)
            ElMessage.error('请求出错，请检查网络或稍后再试')
          })
      })
        .catch(() => {
          ElMessage.info('已取消操作')
        })
    }


    //批次混放不允许按钮
    function toggleAllowBatchMixNo(id) {

      WarehouseareaInfoSwer.zone_id = id;

      WarehouseareaInfoSwer.zone_batch_mixing = '0'

      ElMessageBox.confirm(
        '确认要重置库区下所有库位的批次混放规则吗',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        axios.put(
          'http://localhost:5181/api/Db_warehouse_zone/Warehousezone_BatchMixNO',
          WarehouseareaInfoSwer,
          {
            headers: {
              authorization: `Bearer ${localStorage.getItem('token')}`,

            }
          }
        )
          .then((res) => {

            if (res.data > 0) {
              ElMessage.success(`产品混放规则设置成功`)
              //调用重新查询
              fill();
              //统计方法
              Count();
            } else if (res.data == 0) {
              ElMessage.success(`产品混放规则设置成功`)
            } else {
              ElMessage.error("设置失败，请重试");
            }
          })
          .catch((err) => {
            console.error(err)
            ElMessage.error('请求出错，请检查网络或稍后再试')
          })
      })
        .catch(() => {
          ElMessage.info('已取消操作')
        })
    }

    const handleCapacityChange = (val) => {

      if (enableChangeEvent.value) {

        changeCapacity(val);
      }
      const available = WarehouseareaInfo.zone_available;



      if (available >= val) {
        isDisabled.value = true;

        // 自动修正可用容量
        WarehouseareaInfo.zone_available = val;


      } else {
        isDisabled.value = false;
      }


    }
    //触发器--库区容量
    const changeCapacity = (val) => {
      WarehouseareaInfo.zone_available = val;
     
     
    }

    const changeCapacity_available = (val) => {

      // WarehouseareaInfo.zone_available=val;
      if (val >= WarehouseareaInfo.zone_capacity) {

        isDisabled.value = true;

      }
     
    }

    function close(){
      dialogVisible.value = false;
      //清空数据
      Object.assign(WarehouseareaInfo, intWarehouseInfo)
    }

    //点击添加按钮
function addWarehouseareaInfo(){
      warehousezone_id=0;
      //清空对象数据
      Object.assign(WarehouseareaInfo,intWarehouseInfo)
      dialogVisible.value=ref(true)
    enableChangeEvent.value=true;
}
  
  //点击修改
    function warehouse_zone_update(row){
      
      warehousezone_id = row.zone_id;
      //控制产品的产品混放和批次混放的显示
      isTooltipEnabled.value=true;

      enableChangeEvent.value = false;

      title.value ="修改库区设置"
      //显示侧边栏
      dialogVisible.value=ref(true)
      //不可以进行修改库区编码
      WarehouseareaInfo.isEditMode = true;
    

      //修改数据--一键赋值
      Object.assign(WarehouseareaInfo,row)
      
      WarehouseareaInfo.update_by = localStorage.getItem('userLName')
      WarehouseareaInfo.Update_time = dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ')
      //将库区可用容量解放出来
      isDisabled.value=false

    
      if (WarehouseareaInfo.zone_available >= WarehouseareaInfo.zone_capacity){
        //将库区可用容量禁用
        isDisabled.value = true;
      }
      
    }

    //点击编码显示模态框,查看详细信息
    function detail(row) {
      dialogVisibleSwer.value = true;
      //修改数据--一键赋值
      Object.assign(WarehouseareaInfo, row)
    } 

    //模态取消
    function gbmtk() {
      dialogVisibleSwer.value = false;
      //清空数据
      Object.assign(WarehouseareaInfo, location)
    }

    function confirmLoss() {
      dialogVisibleSwer.value = false;
      //清空数据
      Object.assign(WarehouseareaInfo, location)

    }


    //编码自动生成
function handleAutoGenerateCodeChange(value){
  if (value === '1') {
      // 开启自动生码
      axios.get("http://localhost:5181/api/DJBH/DJBH",{
        params:{
          en_code:4
        },headers:{ 
          authorization: `Bearer ${localStorage.getItem('token')}`,
        }
      }).then((res)=>{
        WarehouseareaInfo.zone_code =res.data;
      // 手动触发验证
       ruleFormRef.value.validateField('zone_code', (valid) => {
      if (valid) {
        console.log('验证通过');
      } else {
        console.log('验证失败');
      }
    });
      }).catch((err)=>{
        console.log(err);
      })
    } else {
      // 关闭自动生码，清空编码
      WarehouseareaInfo.zone_code = '';
    }
}

    // 每页数量变化--选择传递每页显示数
  const handleSizeChange = (newSize) => {
    pageSize.value = newSize;
    //重新按照pageSize和currentPage重新请求数据
    fill();
  };
  
  // 当前页变化
  const handleCurrentChange = (newPage) => {
    currentPage.value=newPage;
    //重新按照pageSize和currentPage重新请求数据
    fill();
  };
  
//点击查询方法
function  queryZone(){
//输入zone_name,重新查询
fill();
//统计方法
Count();
}
//重置按钮
function  reset(){
//清空输入框
zone_name.value="";
//重新查询
fill();
//统计方法
Count();
}

//点击切换冻结状态-仓库库区
function toggleFreeze(row) {
 if(row.zone_freeze==0){
   ElMessageBox.confirm(
     `你确定要冻结${row.zone_name}`,
     '提示',
     {
       confirmButtonText: '确定',
       cancelButtonText: '取消',
       type: 'warning'
     }
   ).then(()=>{
     axios.put("http://localhost:5181/api/Db_warehouse_zone/warehouseZone_Frozenstate", {},
       {
         params: {
           id: row.zone_id,
           zone_freeze: row.zone_freeze
         },
         headers: {
           authorization: `Bearer ${localStorage.getItem('token')}`,
         }
       }
     ).then((res => {
       ElMessage.success('冻结成功')
       fill()
     })
     ).catch((err) => {
       console.log(err)
     })
   })
}else{
   ElMessageBox.confirm(
     `你确定要解冻${row.zone_name}`,
     '提示',
     {
       confirmButtonText: '确定',
       cancelButtonText: '取消',
       type: 'warning'
     }
   ).then(() => {
     axios.put("http://localhost:5181/api/Db_warehouse_zone/warehouseZone_Frozenstate", {},
       {
         params: {
           id: row.zone_id,
           zone_freeze: row.zone_freeze
         },
         headers: {
           authorization: `Bearer ${localStorage.getItem('token')}`,
         }
       }
     ).then((res => {
       ElMessage.success('解冻成功')
       fill()
     })
     ).catch((err) => {
       console.log(err)
     })
   })

}
}


  
  //分页方法
  function fill(){
    axios.get("http://localhost:5181/api/Db_warehouse_zone/WarehouseZoneFY",{
      params:{
        warehouse_code:warehouse_codego.value,
        zone_name:zone_name.value,
        currentPage:currentPage.value,
        pageSize:pageSize.value
      },
      headers:{
        authorization: `Bearer ${localStorage.getItem('token')}`,
      }
    }).then((result) => {
      tableData.value=result.data;
      console.log(tableData.value);
    }).catch((err) => {
                console.info(err)
    })
  }
  
  //查询总数
  function Count(){
    axios.get("http://localhost:5181/api/Db_warehouse_zone/warehousezoneCount",{
      params:{
        warehouse_code:warehouse_codego.value,
        zone_name:zone_name.value,
      },
      headers:{
        authorization: `Bearer ${localStorage.getItem('token')}`,
      }  
    }).then((result) => {
              pageCount.value=result.data
            
    }).catch((err) => {
                console.info(err)
    })
  }
  
    onMounted(()=>{
      fill();
      Count();
    })
    </script>
  
  
  
    <style scoped>
  .block {
    display: flex;
    justify-content: center;

    margin-top: 20px;
  }

    .action-buttons {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      /* 按钮间距 */
    }

    /* 响应式调整 */
    @media (max-width: 1600px) {
      .action-buttons {
        gap: 4px;
      }

      .action-buttons .el-button {
        padding: 6px 8px;
        font-size: 12px;
      }
    }

    .el-button--primary {
      position: relative;

    }

    .button-group {
      display: flex;
      margin-top: 10px;
      margin-bottom: 10px;
    }

    .dept_title {
      float: left;
      font-weight: bold;
      margin-top: -10px;
      font-size: 20px;
    }

    .dept_where {
      display: left;
      margin-left: -680px;
      margin-top: -30px;
      margin-bottom: 20px;
    }

    .dept_input {
      margin-right: 40px;
    }

    .switch-wrapper {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 12px;
    }

    .status-label {
      font-weight: 500;
      min-width: 90px;
      text-align: center;
      font-size: 13px;
      color: #333;
    }

    /* 开关容器 */
    .switch-display {
      position: relative;
      width: 50px;
      height: 24px;
      border-radius: 12px;
      background-color: #dcdfe6;
      /* 默认灰色背景 */
      cursor: pointer;
      user-select: none;
      transition: background-color 0.3s ease;
    }

    /* 开启状态样式 */
    .switch-display.switch-on {
      background-color: #409eff;
      /* 正常蓝色表示开启 */
    }

    /* 滑块样式 */
    .slider {
      position: absolute;
      width: 22px;
      height: 22px;
      border-radius: 50%;
      background-color: white;
      top: 1px;
      transition: left 0.3s ease;
    }



    /* 关闭状态滑块位置 */
    .switch-display .slider {
      left: 1px;
    }

    /* 开启状态滑块位置 */
    .switch-display.switch-on .slider {
      left: calc(100% - 23px);
      /* 让滑块移动到右边 */
    }


  </style>